package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.anno.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    private final UserInfoService userInfoService;

    @Autowired
    public WxLoginApiController(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    /**
     * @description: 小程序授权登录
     * @author Petrichor
     * @date 2023/12/23 20:13
     * @param code 前端传来的 临时登录凭证
     * @return 自定义登陆状态
    **/
    @Operation(summary = "小程序授权登录")
    @GetMapping(value = "/wxLogin/{code}")
    public Result<Map<String , String>>  wxLogin(@PathVariable(value = "code") String code) {
        Map<String , String> result = userInfoService.wxLogin(code) ;
        return Result.build(result , ResultCodeEnum.SUCCESS) ;
    }
    /**
     * @description: 获取登录信息
     * @author Petrichor
     * @date 2023/12/23 20:56
     * @return 用户登录信息
    **/
    @GuiGuLogin
    @Operation(summary = "获取登录信息")
    @GetMapping("/getUserInfo")
    public Result<UserInfoVo> getUserInfo(){
        //  获取到用户Id
        Long userId = AuthContextHolder.getUserId();
        //  调用服务层方法
        UserInfoVo userInfoVo = userInfoService.getUserInfoVoByUserId(userId);
        //  返回数据
        return Result.ok(userInfoVo);
    }
    /**
     * @description: 更新用户信息
     * @author Petrichor
     * @date 2023/12/23 22:27
     * @param userInfoVo 用户信息
     * @return
    **/
    @GuiGuLogin
    @Operation(summary = "更新用户信息")
    @PostMapping("updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){

        //  获取到用户Id
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());

        //  执行更新方法
        userInfoService.updateById(userInfo);

        return Result.ok();
    }
}
